package com.codefish.util;


import com.aliyun.oss.OSSClient;
import com.codefish.config.AliyunClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;


@Component
public class SmsUtil {

    private static final Logger log = LoggerFactory.getLogger(SmsUtil.class);

    @Autowired
    private AliyunClient aliyunClient;


    public R sendSms(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunClient.getAccessKeyId(), aliyunClient.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", aliyunClient.getSignName());
        request.putQueryParameter("TemplateCode", aliyunClient.getSmsCode());
        request.putQueryParameter("TemplateParam", "{\"code\":\"[value]\"}".replace("[value]", code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
            return R.error();
        } catch (ClientException e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }
}
